<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\adminchy\controller;

use app\adminchy\model\NodeModel;
use app\adminchy\model\RoleModel;
use think\Controller;
use think\Db;

class Base extends Controller
{
    public function __empty(){
        $this->redirect('adminchy/Login/index');
    }
    public function __construct()
    {
        parent::__construct();
        if (empty(session('user.id'))) {
            $loginUrl = url('login/index');
            if (request()->isAjax()) {
                return msg(111, $loginUrl, '登录超时');
            }
            return $this->redirect($loginUrl);
        }
        $control = strtolower(request()->controller());
        $action = strtolower(request()->action());
        $uid = session('user.id');
        $res = $this->authCheck($control,$action,$uid);
        if($res===false){
            return $this->error('您没有权限访问！','/adminchy/Index/indexMain');
        }
    }

    /**
     * 权限检测
     * @param $rule
     */
    function authCheck($control,$action,$uid)
    {
        //首页所有人都有权限
        if($control=='index'){
            return true;
        }
        $role_id = Db::name('snake_user')->where(['id' =>$uid])->value('role_id');
        $role = RoleModel::where('id', $role_id)->find();
        if ($role['rule'] == '*') {
            //所有权限
            return true;
        }
        $node = [];
        if ($role['rule']) {
            if (strpos($role['rule'], ',') !== false) {
                $node = explode(',', $role['rule']);
            }else{
                $node[] = $role['rule'];
            }
        } else {
            //没有任何权限
            return false;
        }
        $pass = 0;
        foreach ($node as $v) {
            $node_info = NodeModel::where('id', $v)->find();
            if ($node_info['control_name'] == $control && $node_info['action_name'] == $action) {
                $pass = 1;
                break;
            }
        }
        if($pass==1){
            return true;
        }else{
            return false;
        }
    }
}